/*  PCSX2 - PS2 Emulator for PCs
 *  Copyright (C) 2002-2010  PCSX2 Dev Team
 *
 *  PCSX2 is free software: you can redistribute it and/or modify it under the terms
 *  of the GNU Lesser General Public License as published by the Free Software Found-
 *  ation, either version 3 of the License, or (at your option) any later version.
 *
 *  PCSX2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 *  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 *  PURPOSE.  See the GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along with PCSX2.
 *  If not, see <http://www.gnu.org/licenses/>.
 */

#include "PrecompiledHeader.h"
#include "ConfigurationDialog.h"
#include "System.h"

#include <wx/filepicker.h>
#include <wx/ffile.h>

using namespace pxSizerFlags;

Dialogs::RenameGame::RenameGame( wxWindow* parent, const wxFileName& game, const bool& isTCompressed )
	: wxDialogWithHelpers( parent, _("Rename Game") )
	, m_game( game )
	, m_compressed( isTCompressed )
{
	wxBoxSizer& s_buttons( *new wxBoxSizer(wxHORIZONTAL) );
	s_buttons += new wxButton( this, wxID_CANCEL )			| pxProportion(2);
	s_buttons += pxStretchSpacer(3);
	s_buttons += new wxButton( this, wxID_OK, _("Rename") )	| pxProportion(2);

	wxBoxSizer& s_panel( *new wxBoxSizer(wxVERTICAL) );

	RenameBox  = CreateNumericalTextCtrl(this, 40, wxTE_LEFT);

	s_panel += RenameBox  | StdCenter();
	s_panel += 5;
	s_panel += s_buttons  | StdCenter();

	*this += s_panel | StdExpand();

	RenameBox->SetValue(m_game.GetName());

	Connect( wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler( RenameGame::OnOk_Click ) );
}

void Dialogs::RenameGame::OnOk_Click( wxCommandEvent& evt )
{
	wxString renamedgame(Path::Combine(m_game.GetPath(), RenameBox->GetValue()));
	wxString result( renamedgame + L"." + m_game.GetExt());
	wxString resultCon( RenameBox->GetValue() + L"." + m_game.GetExt());
	if (wxFopen(renamedgame, L"r+b"))
	{
		wxString content;
		if(!content.IsEmpty()) content.Clear();
		content.Printf( _T( "%s found on disk. Delete %s?"), resultCon, resultCon );
		if( !Msgbox::YesNo( content, _("Warning") ) ){ EndModal( wxID_OK ); return; }
	}

	//const bool UtRename( wxRenameFile( m_game.GetFullPath(), result ));
	if(!wxRenameFile( m_game.GetFullPath(), result ))
	{
		Console.Error("Error rename %s to %s", m_game.GetFullName().char_str(), resultCon.char_str());
		EndModal( wxID_OK );
		return;
	}
	if(m_compressed)
	{
		//const bool TRename( wxRenameFile( m_game.GetFullPath() + L".table", result + L".table" ));
		if(!wxRenameFile( m_game.GetFullPath() + L".table", result + L".table" ))
		{
			Console.Error("Error rename %s.table to %s.table", m_game.GetFullName().char_str(), resultCon.char_str());
		}
	}
	EndModal( wxID_OK );
}